package com.totoro.mongo.collection;

import com.totoro.mongo.exception.NotFoundDataException;
import com.totoro.mongo.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

/**
 * 处理微信重复账号的入口。需要做到的内容有：
 * 1、程序可控，随时启动，停止
 * 2、执行速率可控，避免执行太快占用数据库太多io
 * 3、不能重复执行
 */
@RestController
public class DealWechatDisableController {
    private static final Logger LOGGER = LoggerFactory.getLogger(DealWechatDisableController.class) ;

    @Resource
    private AccountService accountService ;

    private static Future task = null ;// 收集数据的任务

    private static Future dealTask = null ; //处理数据的任务

    private static ExecutorService dealService = Executors.newFixedThreadPool(2, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r) ;
            thread.setDaemon(true);
            return thread ;
        }
    });



    /**
     * 开始收集错误的数据
     * @param limit
     * @param sleepSecond
     */
    @GetMapping("/wechat/collect/start")
    public String collectData(final int limit, final long sleepSecond){
        if(task != null){
            return  "服务已在运行，请勿重复操作！";
        }

        task = dealService.submit(new Runnable() {
            @Override
            public void run() {
                while(true){
                    String skip = accountService.getQuerySkipSchedule() ;
                    LOGGER.info("执行一次收集数据_id从{}处开始：", skip);
                    try {
                        accountService.collectData(skip, limit);
                        Thread.sleep(sleepSecond);
                    } catch (NotFoundDataException e) {
                        LOGGER.info("数据收集完毕！");
                        return ;
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                        return ;
                    } catch (Exception e) {
                        e.printStackTrace();
                        //停止执行
                        return ;
                    }
                }

            }
        });
        return "成功启动服务" ;
    }

    /**
     * 停止收集错误信息
     * @return
     */
    @GetMapping("/wechat/collect/stop")
    public String stopCollectData(){
        if(task == null){
            return "收集数据服务已停止，请勿重复操作！" ;
        }

        LOGGER.info("开始停止收集数据服务！");

        task.cancel(true) ;
        task = null ;

        return "停止收集数据服务成功！" ;
    }

    @GetMapping("/wechat/deal/start")
    public String dealData(final int limit, final int sleepSecond){
        if(dealTask != null){
            return "已经在处理数据，请勿重复操作！" ;
        }
        dealTask = dealService.submit(new Runnable() {
            @Override
            public void run() {
                while(true){
                    String skip = accountService.getDealSkipSchedule() ;
                    LOGGER.info("执行一次数据处理_id从{}处开始：", skip);
                    try {
                        accountService.dealData(skip, limit);
                        Thread.sleep(sleepSecond);
                    } catch (NotFoundDataException e) {
                        LOGGER.info("数据处理完毕！");
                        return ;
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                        return ;
                    } catch (Exception e) {
                        e.printStackTrace();
                        //停止执行
                        return ;
                    }
                }

            }
        }) ;
        return "处理服务已启动！" ;
    }

    @GetMapping("/wechat/deal/stop")
    public String stopDeal() {
        if(dealTask == null){
            return "处理服务已停止，请勿重复操作！" ;
        }

        LOGGER.info("开始停止处理数据服务！") ;
        dealTask.cancel(true) ;
        dealTask = null ;

        return "停止处理数据服务成功！" ;
    }
}
